<template>
  <div class="order-measure-detail">
    <header>
      <div class="left">
        <p>测量单编号：{{ detail.measureOrderNo || "-" }}</p>
        <p class="ml32">关联订单编号：{{ detail.orderNo || "-" }}</p>
        <p class="ml32">下单时间：{{ detail.createTime || "-" }}</p>
        <p class="ml32">测量时间：{{ detail.measureTime || "-" }}</p>
      </div>
      <div class="right">
        <el-button type="primary" v-if="detail.businessState === 1" link @click="clickCancel()">撤销订单</el-button>
        <template v-if="detail.businessState === 3">
          <el-button type="primary" link @click="toQuotePrice">生成增减项</el-button>
          <el-divider direction="vertical" />
          <el-button
            type="primary"
            link
            @click="
              toPath({
                path: '/regular-time-procure',
                query: { orderId: detail.orderId, factorId: detail.factoryId, isNow: '1' }
              })
            "
            >生成采购单</el-button
          >
        </template>

        <el-button type="danger" v-if="detail.businessState === 4" link @click="clickDel()">删除</el-button>

        <!-- <el-divider direction="vertical" /> -->
        <!-- <el-button type="primary" link @click="back">返回</el-button> -->
      </div>
    </header>
    <div class="content">
      <!-- 测量状态 -->
      <div class="detail-status">
        <h1 class="orange" v-if="detail.businessState === 1">待接单</h1>
        <h1 class="orange" v-if="detail.businessState === 2">待测量</h1>
        <h1 class="green" v-if="detail.businessState === 3">已测量并定价</h1>
        <h1 class="gray" v-if="detail.businessState === 4">已撤销</h1>
      </div>

      <!-- 订单信息 -->
      <div class="order-info">
        <!-- 测量地址 -->
        <div class="info1 mb20">
          <p class="title">测量地址</p>
          <el-row>
            <el-col :span="5">
              <b>姓名：{{ detail.receivingName || "-" }}</b>
            </el-col>
            <el-col :span="5">
              <b>电话：{{ detail.receivingMobile || "-" }}</b>
            </el-col>
            <el-col :span="14">
              <b>地址：{{ detail.receivingAddress || "-" }}</b>
            </el-col>
          </el-row>
        </div>
        <!-- 关联客户 -->
        <div class="info2 mb20">
          <p class="title">关联客户</p>
          <el-row>
            <el-col :span="5">
              <b>姓名：{{ detail.customerName || "-" }}</b>
            </el-col>
            <el-col :span="5">
              <b>电话：{{ detail.customerMobileCode || "-" }}</b>
            </el-col>
            <el-col :span="14">
              <b>地址：{{ detail.customerAddress || "-" }}</b>
            </el-col>
          </el-row>
        </div>
        <!-- 开票/税额 -->
        <div class="info2 mb20">
          <p class="title">开票/税额</p>
          <el-row>
            <el-col :span="5">
              <b style="color: #ff3333">是否开票：{{ detail.isBusinessInvoice === 1 ? "是" : "否" }}</b>
            </el-col>
            <el-col :span="19">
              <b>税额（当前）：¥{{ detail.invoiceAmount || "-" }}</b>
            </el-col>
          </el-row>
        </div>
        <!-- 企业信息 -->
        <div class="info3 mb20">
          <p class="title">{{ detail.merchantName || "-" }}</p>
          <el-row>
            <el-col :span="5">
              <b>跟单人员：{{ detail.trackerName || "-" }}</b>
            </el-col>
            <el-col :span="5">
              <b>跟单人电话：{{ detail.trackerTel || "-" }}</b>
            </el-col>
            <el-col :span="5">
              <b>工厂地址：{{ detail.factorAddress || "-" }}</b>
            </el-col>
            <el-col :span="9">
              <b style="color: #ff3333">
                是否支持开票：（专票：{{ detail.specialTicket }}%）（普票：{{ detail.ordinaryTicket }}%）
              </b>
            </el-col>
          </el-row>
        </div>
        <!-- 测量预购单备注 -->
        <div class="info3 mb20">
          <p class="title">测量预购单备注</p>
          <div>
            <b style="font-weight: normal; color: #1a1a1a">
              <div class="remark-info" v-html="detail.remark"></div>
            </b>
          </div>
        </div>
      </div>
      <div class="block"></div>
      <!-- 商品信息 -->
      <p class="f18 mb14" style="color: #131414">商品信息</p>
      <div class="prod-info">
        <el-table class="jzt-table" :data="list" border stripe style="width: 100%">
          <el-table-column prop="date" show-overflow-tooltip label="商品信息" width="400">
            <template #default="scope">
              <div class="col1">
                <div>
                  <div class="left">
                    <img :src="scope.row.mainPicUrl" alt="" />
                  </div>
                  <div class="right">
                    <h3 class="name">{{ scope.row.productAliasName }}</h3>
                    <p style="white-space: break-spaces">{{ scope.row.skuSpecification }}</p>
                    <p>SKU编码：{{ scope.row.skuCode || "-" }}</p>
                    <p>ID:{{ scope.row.productId || "-" }}</p>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="productRemark" show-overflow-tooltip label="备注" width="240">
            <template #default="scope">
              <!-- <span>{{ scope.row.productRemark || "-" }}</span> -->
              <RemarkEditor v-model="scope.row.productRemark" :isEdit="false" />
            </template>
          </el-table-column>
          <el-table-column prop="supplyUnitPrice" show-overflow-tooltip label="供应单价" width="160" />
          <el-table-column prop="commodityNum" show-overflow-tooltip label="数量" />
          <el-table-column prop="detailNum" show-overflow-tooltip label="件数" />
          <el-table-column prop="measureDataRemark" show-overflow-tooltip label="测量数据反馈" width="280">
            <template #default="scope">
              <div class="text-over2">
                {{ scope.row.measureDataRemark || "-" }}
              </div>
              <el-button type="primary" link @click="clickOpenMeasure(scope.row, 'view')">查看更多</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="measurePrice" show-overflow-tooltip label="测量后定价" width="180">
            <template #default="scope">
              <div class="measure-price">
                <el-input-number
                  v-if="detail.businessState === 2 || (detail.businessState === 3 && isAllowEdit)"
                  class="jzt-input-number jzt-input-number-hidden"
                  v-model="scope.row.measurePrice"
                  :min="0"
                  :max="99999999"
                  controls-position="right"
                />
                <span v-else>¥{{ scope.row.measurePrice || "-" }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="dealState" fixed="right" show-overflow-tooltip label="状态" width="120">
            <template #default="scope">
              <p v-if="scope.row.businessState === 1"><el-tag type="warning">待接单</el-tag></p>
              <p v-if="scope.row.businessState === 2"><el-tag type="warning">待测量定价</el-tag></p>
              <p v-if="scope.row.businessState === 3"><el-tag type="success">已测量并定价</el-tag></p>
              <p v-if="scope.row.businessState === 4"><el-tag type="info">已撤销</el-tag></p>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 金额、费用 -->
      <footer>
        <div>
          <div class="pay2">
            <p>
              <span>供应单价合计：</span><b>¥{{ detail.totalSupplyUnitPrice }}</b>
            </p>
            <h3>
              <span>测量后定价合计：</span><b>¥{{ detail.totalMeasurePrice }}</b>
            </h3>
          </div>
        </div>
      </footer>
    </div>
    <!-- 图片文件预览 -->
    <el-dialog v-model="dialogVisibleImg" title="图片文件预览" width="500">
      <img :src="reviewImgUrl" alt="" style="width: 100%" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibleImg = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 撤销订单-二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenCancel"
      :title="'撤销确认'"
      :message="'您正在执行撤销测量单操作，撤销后，供应商将无法在接单，以及进行测量服务，是否要继续撤销当前订单？'"
      :submitBtnText="'继续撤销'"
      @submit="returnSubmitCancel"
    />

    <!-- 确认删除 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenDel"
      :message="'您正在执行删除当前订单操作，删除后，当前订单将不在显示，是否继续删除？'"
      :submitBtnText="'确认删除'"
      @submit="returnSubmitDel"
    />

    <!-- 测量数据反馈-抽屉 -->
    <MeasureDrawer v-model:isOpen="_isOpenMeasure" :optionInfo="optionInfo" @submitOk="measureSubmitOk" />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { Edit } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import useCodeArrStore from "@/store/modules/select";
import word from "@/assets/word.png";
import pdf from "@/assets/pdf.png";
import RemarkEditor from "@/components/RemarkEditor";
import { ElMessage } from "element-plus";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import CountdownMy from "./components/countdown";
import MeasureDrawer from "./components/measureDrawer.vue";
import { getMeasureDetails, inputData, cancelOrder, measureOrderDel } from "@/apis/order/measure";

const isAllowEdit = ref(false); //编辑状态下 是否允许编辑（只有点击了编辑按钮才可以编辑）
const list = ref([]);
const measureOrderId = ref(route.query.measureOrderId);
const detail = ref({});
const redirect = ref("");
const _isOpenCancel = ref(false);
const dialogVisibleImg = ref(false);
const reviewImgUrl = ref("");
const _isOpenDel = ref(false);
const _isOpenMeasure = ref(false); //测量数据反馈-抽屉
const optionInfo = ref({ detail: {} });
const currObj = ref({}); //测量数据 当前行数据

onMounted(() => {
  redirect.value = route.query.redirect;
  getDetailFun();
});

//打开新的页签
const toPath = obj => {
  const routeUrl = router.resolve(obj);
  window.open(routeUrl.href, "_blank");
};

//跳转到设计师商城-预算报价详情页
const toQuotePrice = () => {
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/designer/quote-price/following/list",
    query: { ysId: detail.value.ysId, budgetId: detail.value.budgetId, templateId: detail.value.templateId }
    // query: { ysId: "1829785907958050816", budgetId: "1838502976132149248", templateId: "1831965627432759296" }
  });
  window.open(routeUrl.href, "_blank");
};

//测量数据回馈-抽屉
const clickOpenMeasure = (row, type = "edit") => {
  currObj.value = row;
  optionInfo.value.type = type;
  optionInfo.value.detail = {
    ...row,
    _time: new Date()
  };
  _isOpenMeasure.value = true;
};

//测量数据回馈-抽屉-保存回调
const measureSubmitOk = newRow => {
  console.log("编辑之后的商品信息===", newRow);
  list.value.map(item => {
    if (item.orderDetailId === newRow.orderDetailId) {
      item.measureDataRemark = newRow.measureDataRemark;
      item.measureUrl = newRow.measureUrl;
    }
  });
  console.log("重新赋值后的list===", list.value);
};

//删除弹窗打开
const clickDel = () => {
  _isOpenDel.value = true;
};
//确认删除
const returnSubmitDel = () => {
  measureOrderDel({ measureOrderId: detail.value.measureOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      _isOpenDel.value = false;
      back();
    }
  });
};

//接单弹窗打开
const clickCancel = () => {
  _isOpenCancel.value = true;
};
//撤销测量单
const returnSubmitCancel = () => {
  cancelOrder({ measureOrderId: detail.value.measureOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "测量单撤销成功",
        type: "success"
      });
      getDetailFun();
      _isOpenCancel.value = false;
    }
  });
};

const getFileType = url => {
  const fileArr = ["doc", "docx", "pdf"];
  const fileSuffix = url?.split(".")[url?.split(".").length - 1] || "";
  const type = fileArr.includes(fileSuffix.toLowerCase()) ? "file" : "img";
  return type;
};

const reviewFile = url => {
  const type = getFileType(url);
  console.log("这个文件是==", type);
  if (type === "file") {
    // 文件下载
    downloadFile(url || "");
  } else if (type === "img") {
    // 图片预览
    reviewImgUrl.value = url;
    dialogVisibleImg.value = true;
  }
};

/**
 * 下载附件
 */
const downloadFile = url => {
  console.log("这是下载附件操作", url);
  if (!url) return;
  const urlSplit = url ? url.split("/") : [];
  const name = decodeURIComponent(urlSplit[urlSplit.length - 1]);
  let xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    if (xhr.status === 200) {
      let file = xhr.response;
      let fileName = name;
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(file, fileName);
      } else {
        let fileUrl = window.URL.createObjectURL(file);
        let a = document.createElement("a");
        a.download = fileName;
        a.href = fileUrl;
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
        window.URL.revokeObjectURL(fileUrl);
      }
    }
  };
  xhr.send();
};

const back = () => {
  router.push({
    path: "/order/measure"
  });
};

const getUrl = url => {
  const fileArr = ["doc", "docx"];
  const fileSuffix = url?.split(".")[url?.split(".").length - 1] || "";
  const type = fileArr.includes(fileSuffix.toLowerCase()) ? "doc" : fileSuffix.toLowerCase() === "pdf" ? "pdf" : "img";
  return type === "pdf" ? pdf : type === "doc" ? word : url;
};

const getName = (key, value) => {
  return useCodeArrStore().getDictName(key, value) || "-";
};

//获取测量单详情
const getDetailFun = () => {
  getMeasureDetails({ measureOrderId: measureOrderId.value }).then(res => {
    if (res.code === 200) {
      detail.value = res.data;
      // detail.value.businessState = 2;
      list.value = res.data.orderDetailList || [];
      console.log("订单详请===", res.data);
    }
  });
};
</script>

<style lang="scss" scoped>
.remark-info {
  img {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    margin: 10px 10px 0 0;
  }
  video {
    width: 130px;
    height: 80px;
  }
}
.measure-price {
  :deep(.el-input__wrapper) {
    background-color: white;
  }
}
.block {
  height: 20px;
  margin: 32px -20px;
  background-color: #f5f7fa;
}
.orange {
  color: #ff9900;
}
.green {
  color: #19cc15;
}
.gray {
  color: #86909c;
}
.order-measure-detail {
  height: calc(100% - 20px);
  overflow-y: auto;
  padding: 0 20px 20px 20px;
  & > header {
    padding: 20px;
    margin: 0 -20px;
    display: flex;
    justify-content: space-between;
    position: sticky;
    top: 0;
    background-color: white;
    border-radius: 10px 10px 0 0;
    border-bottom: 1px solid #d8d8d8;
    z-index: 22;
    .left {
      display: flex;
    }
  }
  .steps {
    height: 70px;
  }
  .content {
    :deep(.el-steps) {
      // padding-left: 16%;
      .el-step__icon-inner {
        font-weight: normal;
      }
      .el-step {
        position: relative;
        flex-basis: 40% !important;
        .el-step__head.is-success {
          border-color: transparent;
          .el-step__line {
            height: 0;
            background-color: transparent;
          }
          .el-step__icon.is-text {
            background-color: #e8f3ff;
            color: #165dff;
          }
        }
        .el-step__head.is-process {
          .el-step__icon.is-text {
            border: none;
            background-color: #165dff;
            color: white;
            .el-step__icon-inner {
              font-weight: normal;
            }
          }
        }
        .el-step__head.is-wait {
          .el-step__icon.is-text {
            border: none;
            background-color: #f2f3f5;
            color: #4e5969;
          }
        }
        .el-step__title.is-wait {
          color: #4e5969;
        }
        .el-step__main {
          position: absolute;
          top: -8px;
          left: 40px;
          width: 200px;
          .el-step__title {
            font-weight: normal;
            &.is-success {
              color: #4e5969;
            }
          }
          .el-step__description {
            color: #86909c;
          }
        }
        .el-step__line-inner {
          border: none;
        }
        .el-step__line {
          left: 160px;
          right: 25px;
          height: 0px;
          background-color: transparent;
          border-bottom: 1px dashed #d8d8d8;
        }
      }
    }
    .detail-status {
      display: flex;
      justify-content: space-between;
      margin: 10px 0 10px 0;
      h1 {
        font-size: 24px;
      }
      img {
        width: 62px;
        height: 62px;
      }
    }

    .order-info {
      background-color: #f6f8fa;
      border-radius: 4px;
      padding: 20px;
      .title {
        font-size: 16px;
        color: #86909c;
        margin-bottom: 10px;
      }
    }
    .el-col {
      b {
        color: #1a1a1a;
        font-size: 14px;
        font-weight: normal;
      }
    }
    .file-list {
      display: flex;
      flex-wrap: wrap;
      .list-item {
        cursor: pointer;
      }
      img {
        width: 64px;
        height: 64px;
        margin-right: 10px;
      }
    }
    .pay-flag {
      display: flex;
      b {
        display: inline-block;
        width: 75px;
      }
      & > div {
        flex: 1;
      }
    }
    .reject-info {
      padding: 20px;
      border-radius: 4px;
      border: 1px solid #dcdcdc;
      margin-bottom: 20px;
      h3 {
        color: #ff3333;
        margin-bottom: 16px;
        font-size: 18px;
        font-weight: normal;
      }
      p {
        font-size: 14px;
      }
    }
    .logis-info {
      max-height: 300px;
      overflow-y: auto;
      .item {
        background: #f6f8fa;
        border-radius: 4px 4px 4px 4px;
        margin-bottom: 10px;
        header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 20px;
          border-bottom: 1px solid #c2d4e8;
          p {
            padding-left: 12px;
            position: relative;
            &::before {
              position: absolute;
              content: "";
              height: 14px;
              width: 4px;
              background-color: #007dff;
              left: -2px;
              top: 1px;
            }
          }
        }
        .el-row {
          padding: 15px 20px;
        }
      }
    }
    .prod-info {
      .col1 {
        & > div {
          display: flex;
        }

        .left {
          img {
            width: 80px;
            height: 80px;
            border-radius: 4px;
          }
        }
        .right {
          padding-left: 18px;
          .name {
            font-size: 14px;
            color: #3d3d3d;
            margin-bottom: 5px;
          }
          p {
            font-size: 12px;
            color: #86909c;
            margin-bottom: 5px;
          }
        }
      }
    }
    & > footer {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      p,
      h3 {
        text-align: right;
        color: #86909c;
        line-height: 24px;
        margin-bottom: 10px;
        b {
          display: inline-block;
          width: 120px;
          font-weight: normal;
        }
      }
      .pay1 {
        p {
          font-size: 14px;
        }
      }
      .pay2 {
        p {
          color: #3d3d3d;
          font-size: 16px;
        }
        h3 {
          font-size: 18px;
          color: #3d3d3d;
          b {
            color: #ff3333;
          }
        }
      }
    }
  }
}
</style>
